<template>
    <div style="margin: 20px 10px; height: 500px;">
        <a-row :gutter="[10,0]">
            <a-col :span="4">
                <div style="background-color: white; height: 500px">
                    <div class="chooseByAreaBox">
                        <span class="chooseByArea" style="font-weight: 600">按区域筛选</span>
                    </div>

                    <hr>
                    <div class="area-list">
                        <a-tree
                            v-if="provinces.length > 0"
                            default-expand-all
                            :selected-keys="selectedKeys"
                            :tree-data="provinces"
                            @select="onSelect">
                            <template #title="{ title, key }">
                                <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
                                <template v-else>{{ title }}</template>
                            </template>
                        </a-tree>
                    </div>
                </div>
            </a-col>

            <a-col :span="20">
                <a-card
                    :bordered="false"
                    title="历史数据">
                    <!--            表头部分-->
                    <div slot="extra">
                        <a-range-picker @change="timeRangeChange">
                            <a-icon slot="suffixIcon" type="calendar"/>
                        </a-range-picker>

                        <a-select :filter-option="filterOption"
                                  allowClear
                                  placeholder="电子标签编号"
                                  show-search
                                  style="width: 150px;margin-left: 10px;"
                                  @change="(value)=>{selectIndex=value;findSelectedArea()}">
                            <a-select-option v-for="(item,index) in mecnos" :key="index" placeholder="请选择环保编码">
                                {{ item }}
                            </a-select-option>
                        </a-select>


                        <!--                        <a-input-search v-model="keyword" allow-clear enter-button-->
                        <!--                                        placeholder="请输入环保编码"-->
                        <!--                                        style="margin-left: 16px; width: 272px;"-->
                        <!--                                        @search="onSearch"/>-->
                    </div>

                    <a-table :columns="columns" :data-source="data" :pagination="false" rowKey="id">

                        <div slot="timeRangeSlot" slot-scope="item">
                            <span>
                                {{
                                    moment(item.addtime * 1000).format('YYYY-MM-DD HH:mm:ss')
                                }}
                            </span>
                        </div>

                        <div slot="action" slot-scope="item">
                            <a-button size="small" type="danger" @click="deleteHistoryData(item)">删除</a-button>
                        </div>

                    </a-table>

                    <a-pagination v-model="page" :default-current="2"
                                  :pageSize="pageSize"
                                  :pageSizeOptions="['5','10', '20', '30', '40']"
                                  :showSizeChanger="true"
                                  :showTotal="total => `共 ${total} 条`"
                                  :total="total"
                                  show-quick-jumper
                                  @change="onChange" @showSizeChange="onChange"/>
                </a-card>

            </a-col>
        </a-row>

    </div>
</template>

<script>
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {METHOD, request} from "@/utils/request";
import {RESPONSE} from "../../utils/request";


const columns = [
    {
        title: '环保编码',
        key: 'locator_mobile',
        dataIndex: 'locator_mobile',
    },
    {
        title: '机械名称',
        dataIndex: 'cate_name',
        key: 'cate_name',
    },
    {
        title: '所属区域',
        key: 'district',
        dataIndex: 'district',
    },
    {
        title: 'PM10(ug/m³)',
        key: 'pm25',
        dataIndex: 'pm25',
    },
    {
        title: '时间',
        key: 'times',
        scopedSlots: {customRender: 'timeRangeSlot'},
    },
    // {
    //     title: '操作',
    //     key: 'action',
    //     scopedSlots: {customRender: 'action'},
    // }
];


export default {
    name: 'MachineHistory',
    data() {
        return {
            keyword: "",
            columns,
            data: [],
            locale,
            moment,
            page: 1,  // 当前页码
            pageSize: 5, // 每页数量
            total: 0,   // 一共的机器数量
            userID: null,
            timeRange: [],
            provinces: [],   // 当前用户绑定区域
            selectedKeys: [],  // 左侧点击了的节点数组
            mecnos: [],  // 机械编号列表
            selectIndex: null, // 机械编号列表选择的下标
        };
    }, mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        this.refreshList();
        this.getHistoryData(null);
    }, methods: {
        filterOption(input, option) {
            return (
                // 过滤忽略大小写
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        findAreaByKey(area, key) {

            if (area.children != null && area.children.length > 0) {
                // 有子节点查询所有的子节点
                for (let i = 0; i < area.children.length; i++) {
                    let result = this.findAreaByKey(area.children[i], key);
                    if (result != null) {
                        // 找到了直接返回结果
                        return result;
                    }
                }
            }

            // 没有子节点 或者子节点查完了，检查本身节点
            if (area.key === key) {
                // 找到了直接返回结果
                return area;
            } else {
                // 告诉父节点没找到，继续找
                return null;
            }

        },
        findSelectedArea(needGetData = true) {
            let area = null;
            // 查找当前选中的层级
            if (this.selectedKeys.length !== 0) {
                // 左侧区域选中了层级就查询这个层级的设备
                for (let i = 0; i < this.provinces.length; i++) {
                    area = this.findAreaByKey(this.provinces[i], this.selectedKeys[0]);
                    if (area != null) {
                        // 找到了，需要请求就发送请求结束
                        if (needGetData) {
                            this.getHistoryData(area.title)
                        }

                        return [area.level, this.selectedKeys[0]];
                    }
                }
            } else {
                // 左侧区域没选择就查询所有的设备
                if (needGetData) {
                    this.getHistoryData(null)
                }
                return [null, null];
            }
        },

        // 点击选择了一个区域
        onSelect(selectedKeys, info) {
            console.log(selectedKeys);
            this.selectedKeys = selectedKeys;
            console.log('onSelect', info);
            let keyAndLevel = this.findSelectedArea();
            this.getMachineInfoByArea(keyAndLevel)
        },
        getMachineInfoByArea(keyAndLevel) {
            request("/position/getDzbqByqy", METHOD.GET, {
                id: this.userID,
                sel_level: keyAndLevel[0],
                sel_key: keyAndLevel[1]
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.mecnos = res.data.data;
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },

        refreshList() {
            request("/areas/getAreas?id=" + this.userID, METHOD.GET).then(result => {
                if (result.data.code === 1) {
                    this.provinces = result.data.data;

                    // 只能点击工地所有要给所有的level = 1 or 2 的节点添加一个disabled: true

                    this.provinces.forEach((item) => {
                        item.disabled = true;

                        if (item.children != null) {
                            item.children.forEach((item2) => {
                                item2.disabled = true;
                            })
                        }
                    })
                } else {
                    this.$message.error(result.data.msg);
                }
            })
        },
        timeRangeChange(value) {
            this.timeRange = value;
            this.findSelectedArea();
        },
        onChange(page, pageSize) {
            this.page = page;
            this.pageSize = pageSize;
            this.findSelectedArea();
        },
        deleteHistoryData(item) {
            let that = this;
            this.$confirm(
                {
                    title: "删除后将不能恢复，确认退出吗?",
                    onOk() {
                        request("/wkhr/deleteWkhrByid?id=" + item.id, METHOD.DELETE).then(res => {
                            if (res.data.code === 1) {
                                that.getHistoryData(null);
                            } else {
                                that.$message.error(res.data.msg);
                            }
                        })
                    }
                }
            )
        },
        getHistoryData: function (gdname) {
            request("/position/getLsitBylocator_mobile", METHOD.GET,
                {
                    page: this.page,
                    pageSize: this.pageSize,
                    id: this.userID,
                    stime: this.timeRange.length === 2 ? parseInt(moment(this.timeRange[0]).valueOf() / 1000) : null,
                    etime: this.timeRange.length === 2 ? parseInt(moment(this.timeRange[1]).valueOf() / 1000) : null,
                    gdname: gdname,
                    locator_mobile: this.mecnos[this.selectIndex]
                }).then(res => {
                if (res.data.code === 1) {
                    this.data = res.data.data.records;
                    this.total = res.data.data.total;
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        onSearch() {
            this.findSelectedArea();
        },
    }
}
</script>

<style lang="less" scoped>
.list-content-item {
    color: @text-color-second;
    display: inline-block;
    vertical-align: middle;
    font-size: 14px;
    margin-left: 40px;

    span {
        line-height: 20px;
    }

    p {
        margin: 4px 0 0;
        line-height: 22px;
    }
}
</style>
